package com.example.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.LoginVm
import com.example.base.BaseActivity
import com.example.config.KeyConfig
import com.example.config.UserConfig
import com.example.livedata.EventConfig
import com.example.home.activity.HomeAct
import com.example.login.R
import com.example.login.databinding.ActivityLoginBinding

/**
 * 登录
 */
class LoginAct : BaseActivity() {

    companion object{
        const val KEY_CONFIG_LOGIN_INTERVAL_TIME = 1 * 1000L * 60 * 60 * 24
    }

    private lateinit var binding: ActivityLoginBinding

    private val loginVm: LoginVm by lazy {
        LoginVm(application)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        // 初始化视图
        initViews()
        addObserve()
    }

    private fun initViews() {

        if (!checkReLogin()){
            navMainAct()
        }

        binding.btnLogin.setOnClickListener {
            // 在点击登录按钮时获取用户输入的内容
            val email = binding.etEmail.text.toString()
            val password = binding.etPassword.text.toString()

            if (checkTestUser(email,password)) return@setOnClickListener

            loginVm.sendRequestWithOkHttp(email, password) { success ->
                if (success) {
                    navMainAct()
                } else {
                    tip("用户名或密码输入错误")
                    return@sendRequestWithOkHttp
                }
            }
        }
    }

    private fun checkTestUser(email: String, password: String): Boolean {
        val isValid = UserConfig.selfMap.any { (name, pwd) ->
            name == email && password == pwd
        }

        if (isValid) {
            navMainAct()
        }
        return isValid
    }



    private fun navMainAct(){
        val intent = Intent(this, HomeAct::class.java)
        startActivity(intent)
        MMKVUtil.putLong(KeyConfig.KEY_USER_HAD_LOGIN, System.currentTimeMillis())
        finish()
    }

    //KEY_CONFIG_LOGIN_INTERVAL_TIME之内没有重新登陆就要重新登陆
    private fun checkReLogin(): Boolean{
        val lastLoginTime = MMKVUtil.getLong(KeyConfig.KEY_USER_HAD_LOGIN)
        if (lastLoginTime == 0L){
            return true
        }

        val intervalTime = System.currentTimeMillis() - lastLoginTime
        return intervalTime > KEY_CONFIG_LOGIN_INTERVAL_TIME

    }

    private fun addObserve(){
        loginVm.liveData.observe(this) { value ->
            when(value){
                EventConfig.EVENT_LOGIN_SUCCESS -> {
                    tip("登陆成功")
                }

                EventConfig.EVENT_LOGIN_FAIL ->{
                    tip("登陆失败")

                }
            }

        }
    }

}